package com.wskj.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

import com.wskj.pojo.User;

public class util {
	//获取Subject
	public static Subject getSubject(){
		//获取工厂对象
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		
		//获取安全管理者对象
		SecurityManager securityManager = factory.getInstance();
		
		//将安全管理放入全局对象
		SecurityUtils.setSecurityManager(securityManager);
		
		//全局对象通过安全管理者生成subject对象：主体，可以是用户也可以是程序
		Subject subject = SecurityUtils.getSubject();
		
		return subject;
	}
	//判断用户名是否正确
	public static boolean login(User user){
		Subject subject = util.getSubject();
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
		
		try {
			subject.login(token);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
	}
	
	//判断用户是否拥有此权限
	public static boolean isPermitted(String permit){
		Subject subject = util.getSubject();
		return subject.isPermitted(permit);
	}

	//判断用户是否拥有此角色
	public static boolean hasRole(String role){
		Subject subject = util.getSubject();
		return subject.hasRole(role);
	}
}
